﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Portal.Cms.Bussiness;
using Portal.Web.Utility;
using Portal.Cms.Model;
using Portal.Utility;
using Portal.Web.Model;
using Portal.Core;
using dtSearch32Lib;
using DocumentSearchServiceModel;
using DocumentSearch32Lib;
using Portal.Systems.Model;
using Portal.Workflow.Bussiness;
using Portal.Cms.Utility;
using System.Data;
using Portal.Workflow.Render;
using Portal.Workflow.Utilities;
using System.Data.SqlClient;
using System.Collections.ObjectModel;

namespace Portal.Cms.Render
{
    public class PreviewCmsDocumentDataRenderBll
    {
        class TabItemCls
        {
            public string Alias;
            public string Subject;
            public TabItemCls()
            {
            }
            public TabItemCls(string _Alias, string _Subject)
            {
                Alias = _Alias;
                Subject = _Subject;
            }
        }

        static string GetPlugInJavascript(string SiteId)
        {
            string ScriptText =
                    " <script language=javascript>\r\n" +
                    "     function ClientStartWorkflow(CmsDataId)\r\n" +
                    "     {\r\n" +
                    "         SiteId='" + SiteId + "';\r\n" +
                    "         AjaxOut = Portal.Cms.Render.PreviewCmsDocumentDataRenderBll.ServerSideCheckStartWorkflow(SiteId,CmsDataId).value;\r\n" +
                    "         if(AjaxOut.Error)\r\n" +
                    "         {\r\n" +
                    "           alert(AjaxOut.InfoMessage);\r\n" +
                    "           return;\r\n" +
                    "         }\r\n" +

                    "         if(confirm('Bạn đã chắc chắn khởi tạo quy trình phát hành bộ bản tin chưa?')==false)return;\r\n" +
                    "         AjaxOut = Portal.Cms.Render.PreviewCmsDocumentDataRenderBll.ServerSideStartWorkflow(SiteId,CmsDataId).value;\r\n" +
                    "         if(AjaxOut.Error)\r\n" +
                    "         {\r\n" +
                    "           alert(AjaxOut.InfoMessage);\r\n" +
                    "           return;\r\n" +
                    "         }\r\n" +
                    "         alert(AjaxOut.InfoMessage);\r\n" +
                    "     }\r\n" +
                    " </script>\r\n" +
                    PlugInWorkflowRender.GetJavascript(SiteId, "content_workflow", "divToolBar", true);
                  
            return ScriptText;
        }

       


        public static AjaxOut Draw(string SiteId)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                string GroupDataId = (string)WebEnvironments.Request(SiteId, "gid");
                string CmsDataId = (string)WebEnvironments.Request(SiteId, "CmsDataId");
                string Back = (string)WebEnvironments.Request(SiteId, "Back");
                string Action = (string)WebEnvironments.Request(SiteId, "Action");
                if (Action == null) Action = "";
                //SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CheckPermission(SiteId, GroupDataPermission.StaticId, GroupDataPermission.funcAccess, GroupDataId, WebSessionUtility.GetCurrentLoginUser().UserId, true);



                string Html =
                   GetPlugInJavascript(SiteId) +
                   "<div id=\"content_workflow\"></div>\r\n"+
                   "<div id=\"divPreviewForm\">\r\n" +
                        DrawPreviewForm(SiteId, GroupDataId, CmsDataId,Action, Back).HtmlContent +
                   "</div>\r\n";

                OAjaxOut.HtmlContent = Html;
            }
            catch (Exception ex)
            {
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = ex.Message.ToString();
            }

            return OAjaxOut;
        }
        public static string BaseSiteUrl
        {
            get
            {
                HttpContext context = HttpContext.Current;
                string baseUrl = context.Request.Url.Authority + context.Request.ApplicationPath.TrimEnd('/');
                return baseUrl;
            }
        }
        [AjaxPro.AjaxMethod()]
        public static AjaxOut DrawPreviewForm(string SiteId, string GroupDataId, string CmsDataId, string Action, string Back)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                WebSessionUtility.CheckSessionTimeOut();
                SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
                GroupDataCls OGroupData = CmsUtility.CreateCmsBussinessProcess(SiteId).CreateCmsProcess(SiteId).CreateGroupDataModel(null, SiteId, GroupDataId);
                CmsDataCls OCmsData = CmsUtility.CreateCmsBussinessProcess(SiteId).CreateCmsProcess(SiteId).CreateCmsDataModel(null, SiteId, CmsDataId);
                if (OCmsData == null) throw new Exception("Tham số không hợp lệ! Truy cập bị cấm!");
                string WorkflowDefId = OCmsData.WorkflowDefId;
                if (string.IsNullOrEmpty(Action)) Action = "info";

                string BackScript = "javascript:window.open('DocumentInputData.aspx?gid=" + OGroupData.GroupDataId + "','_self');";
                if (!string.IsNullOrEmpty(Back))
                {
                    BackScript = "javascript:window.open('"+Back+"','_self');";
                }

                TabItemCls[] TabItems = new TabItemCls[]
                {
                    new TabItemCls("info","Thông tin chung"),                    
                    new TabItemCls("changehistory","Lịch sử thay đổi"),
                };
         
                string Html =
                     "<script language=javascript>\r\n " +

                    "  function ProcessExpandCollapse(Id)\r\n" +
                    "  {\r\n" +
                    "     if(document.getElementById(Id).className=='Collapsed')\r\n" +
                    "     {\r\n" +
                    "         document.getElementById(Id).className='Expanded';\r\n" +
                    "     }\r\n" +
                    "     else\r\n" +
                    "     {\r\n" +
                    "         document.getElementById(Id).className='Collapsed';\r\n" +
                    "     }\r\n" +
                    "  }\r\n" +

                      "     function PreviewVersionCmsData(GroupDataId,CmsDataId,DataSaveHistoryId)\r\n" +
                    "     {\r\n" +
                    "         SiteId='" + SiteId + "';\r\n" +
                    "         AjaxOut = Portal.Cms.Render.PreviewCmsDataRenderBll.ServerPreviewVersionCmsData(GroupDataId, CmsDataId,DataSaveHistoryId).value;\r\n" +
                    "         if(AjaxOut.Error)\r\n" +
                    "         {\r\n" +
                    "           alert(AjaxOut.InfoMessage);\r\n" +
                    "           return;\r\n" +
                    "         }\r\n" +
                    "         window.open(AjaxOut.RetUrl, '_blank'); \r\n" +
                    "     }\r\n" +
                     
                     "  </script>\r\n";

             
                string ProcessBy = "";
                string ButtonRoot = WebConfig.GetButtonIconRoot(OSiteParam);
                bool ActiveWorkflow = !string.IsNullOrEmpty(WorkflowDefId);
                
                Html +=
                   " <input id=txtCheckedCategory type=hidden value=\"" + OCmsData.CategoryIds + "\">\r\n" +
                   " <input id=txtCheckedHotCategory type=hidden value=\"" + OCmsData.HotCategoryIds + "\">\r\n" +
                   " <div id=\"divToolBar\">\r\n"+
                   " <div class=DatabaseFunction>\r\n" +
                   "        <ul>\r\n";
                if (ActiveWorkflow)
                {
                    bool HasStarted = WorkflowUtilities.CheckHasStartWorkflow(SiteId, CmsDataId);

                    Portal.Workflow.Bussiness.WorkflowBll.GetWorkflowCls
                        OWorkFlowInfo = WorkflowBll.GetWorkflowActionInfo(OSiteParam.ConnectionString, WorkflowDefId, CmsDataId);
                    if (OWorkFlowInfo != null)
                    {

                        if (OWorkFlowInfo.IsViewer == false)
                        {
                            Html +=
                                AjaxWorkflowTaskNextLink.GetLinkButton(SiteId, OWorkFlowInfo.WorkflowDefId, OWorkFlowInfo.WorkflowActionId, CmsDataId);
                        }
                        else
                        {
                            ProcessBy = "<div class=CssCurrentProcessBy>Đang xử lý bởi: " + OWorkFlowInfo.CurrentProcessFullName + "</div>\r\n";
                        }
                    }
                }

                Html +=
                   "            <li onclick=\"" + BackScript + "\"><img class=image src=\"" + ButtonRoot + "/back.png\"><div>Quay lại</div></li>\r\n" +
                   "        </ul>\r\n" +
                   "  </div>\r\n" +
                   "</div>\r\n" +

                   "<div class=tab>\r\n" +
                    "   <ul>\r\n";
                for (int iIndex = 0; iIndex < TabItems.Length; iIndex++)
                {
                    if (TabItems[iIndex].Alias.ToLower().Equals(Action.ToLower()))
                    {
                        Html += "    <li class=active>" + TabItems[iIndex].Subject + "</li>\r\n";
                    }
                    else
                    {
                        Html += "    <li><a href=\"PreviewCmsDocumentData.aspx?gid=" + GroupDataId + "&CmsDataId=" + OCmsData.DataId + "&back=" + Back + "&action=" + TabItems[iIndex].Alias + "\">" + TabItems[iIndex].Subject + "</a></li>\r\n";
                    }
                }
                Html += "</ul>\r\n" +
                        "</div>\r\n" +


                   "<div class=CssFormSaveUpdate>\r\n" +
                   "  <input type=hidden id=txtDataId value=\"" + CmsDataId + "\">\r\n" +
                    //"  <h3>Thêm mới dữ liệu</h3>\r\n" +
                   "  <div id=divCallSaveAddDataProcessing class=CssProcessing></div>\r\n";
                string HttpDataRoot = WebConfig.HttpDataRoot(OSiteParam);
                if (Action.Equals("info"))
                {
                    string DownloadText = "<a href=\"" + OCmsData.GetAttachDocUrl(SiteId, HttpDataRoot) + "\">Tải về máy</a>";
                    if (string.IsNullOrEmpty(OCmsData.AttachDoc))
                    {
                        DownloadText = "(Chưa có tài liệu gắn kèm)";
                    }
                    Html +=
                   "  <table>\r\n";
                    if (!string.IsNullOrEmpty(ProcessBy))
                    {
                        Html +=
                           "    <tr>\r\n" +
                           "        <td class=c1></td>\r\n" +
                           "        <td class=c2>" + ProcessBy + "</td>\r\n" +
                           "    </tr>\r\n";
                    }
                    Html +=
                       "    <tr class=\"c1\">\r\n" +
                       "        <td class=c1>Số văn bản:</td>\r\n" +
                       "        <td class=c2>" + OCmsData.Subject + "</td>\r\n" +
                       "    </tr>\r\n" +
                       //"    <tr>\r\n" +
                       //"        <td class=c1>Tiêu đề:</td>\r\n" +
                       //"        <td class=c2>" + OCmsData.Subject + "</td>\r\n" +
                       //"    </tr>\r\n" +
                       "    <tr>\r\n" +
                       "        <td class=c1 style=\"vertical-align:top;\">Trích yếu:</td>\r\n" +
                       "        <td class=c2>\r\n" +
                                        OCmsData.Description +
                       "        </td>\r\n" +
                       "    </tr>\r\n" +

                       //"    <tr class=\"CssRowUrl\">\r\n" +
                       //"        <td class=c1>Url:</td>\r\n" +
                       //"        <td class=c2>" + OCmsData.Url + "</td>\r\n" +
                       //"    </tr>\r\n" +
                       "    <tr>\r\n" +
                       "        <td class=c1>Ngày tạo:</td>\r\n" +
                       "        <td class=c2>" + OCmsData.EntryDate.ToString("dd/MM/yyyy") + "</td>\r\n" +
                       "    </tr>\r\n" +


                         "    <tr>\r\n" +
                         "        <td class=c1>Loại văn bản:</td>\r\n" +
                         "        <td class=c2>" + OCmsData.DocTypeName + "</td>\r\n" +
                         "    </tr>\r\n" +
                         "    <tr>\r\n" +
                         "        <td class=c1>Cơ quan ban hành:</td>\r\n" +
                         "        <td class=c2>" + OCmsData.DocReleaseFromName + "</td>\r\n" +
                         "    </tr>\r\n" +
                         "    <tr>\r\n" +
                         "        <td class=c1>Lĩnh vực:</td>\r\n" +
                         "        <td class=c2>" + OCmsData.DocFieldName + "</td>\r\n" +
                         "    </tr>\r\n" +
                         "    <tr>\r\n" +
                         "        <td class=c1>Người ký:</td>\r\n" +
                         "        <td class=c2>" + OCmsData.DocSignerName + "</td>\r\n" +
                         "    </tr>\r\n" +
                         "    <tr>\r\n" +
                         "        <td class=c1>Trạng thái:</td>\r\n" +
                         "        <td class=c2>" + ((OCmsData.DocStatus.Equals("1")) ? "Còn hiệu lực":"Hết hiệu lực") + "</td>\r\n" +
                         "    </tr>\r\n" +
                         //"    <tr>\r\n" +
                         //"        <td class=c1>Ngày ký:</td>\r\n" +
                         //"        <td class=c2>" + OCmsData.SignDate + "</td>\r\n" +
                         //"    </tr>\r\n" +
                         "    <tr>\r\n" +
                         "        <td class=c1>Ngày ban hành:</td>\r\n" +
                         "        <td class=c2>" + OCmsData.ReleaseDate + "</td>\r\n" +
                         "    </tr>\r\n" +
                         "    <tr>\r\n" +
                         "        <td class=c1>Ngày đăng công báo:</td>\r\n" +
                         "        <td class=c2>" + OCmsData.SignDate + "</td>\r\n" +
                         "    </tr>\r\n" +
                         "    <tr>\r\n" +
                         "        <td class=c1>Ngày hiệu lực:</td>\r\n" +
                         "        <td class=c2>" + OCmsData.EffectedDate + "</td>\r\n" +
                         "    </tr>\r\n" +
                         "    <tr>\r\n" +
                         "        <td class=c1>Ngày hết hiệu lực:</td>\r\n" +
                         "        <td class=c2>" + OCmsData.EndEffectedDate + "</td>\r\n" +
                         "    </tr>\r\n" +
                         "    <tr>\r\n" +
                         "        <td class=c1>Trạng thái tìm:</td>\r\n" +
                         "        <td class=c2>" + (OCmsData.AttachedSearchable == 1 ? "Tìm toàn văn" : "Không tìm toàn văn") + "</td>\r\n" +
                         "    </tr>\r\n" +

                         //"    <tr class=\"CssRowStatus\">\r\n" +
                         //"        <td class=c1>Trạng thái:</td>\r\n" +
                         //"        <td class=c2>" + (OCmsData.IsNew == 1 ? "Tài liệu mới" : "") + "</td>\r\n" +
                         //"    </tr>\r\n" +
                         "    <tr class=\"CssRowAttachFile\">\r\n" +
                         "        <td class=c1>Xem file toàn văn:</td>\r\n" +
                         "        <td class=c2>" + DownloadText + "</td>\r\n" +
                         "    </tr>\r\n" +
                         "  </table>\r\n" +
                       "</div>\r\n";


                    RelationTypeCls[] RelationTypes = RelationTypeProcessBll.ReadingRelationType(SiteId, OCmsData.frkGroupDataId);
                    for (int iIndex = 0; iIndex < RelationTypes.Length; iIndex++)
                    {                        
                        CmsDataRelationCls[] CmsDataRelations = CmsUtility.CreateCmsBussinessProcess(SiteId).CreateCmsProcess(SiteId).ReadingDocumentRelation(SiteId, OCmsData.DataId, RelationTypes[iIndex].RelationTypeId);
                        if (CmsDataRelations.Length > 0)
                        {
                           
                            Html +=
                            " <h3>" + RelationTypes[iIndex].RelationTypeName + "</h3>\r\n" +
                            " <div class=relationdoc>\r\n" +
                            " <ul>\r\n";
                            for (int zIndex = 0; zIndex < CmsDataRelations.Length; zIndex++)
                            { string FileLoacation = HttpDataRoot + "/DocumentArchives/" + "sbv" + "/ArchiveDoc/Archive/" + CmsDataRelations[zIndex].AttachDoc;
                            DownloadText = "<a href=\"" + FileLoacation + "\">" + CmsDataRelations[zIndex].Subject + "</a>";
                                Html +=
                                    "<li>\r\n" +
                                    "    Số: <span class=DocNo>" + DownloadText + "</span> \r\n" +                                    
                                    "</li>\r\n";
                            }
                            Html +=
                            "</ul>\r\n" +
                            "</div>\r\n";
                        }
                    }

                }
                if (Action.Equals("workflow"))
                {
                    Html += DrawWorkflowHistory(SiteId, OCmsData.DataId).HtmlContent;
                }

                if (Action.Equals("changehistory"))
                {
                    Html += DrawChangeHistory(SiteId, OCmsData.DataId).HtmlContent;
                }
                Html+=
                   "<div class=CssTop><a href=\"#top\">Về đầu</a></div>\r\n";


                OAjaxOut.HtmlContent = Html;
            }
            catch (Exception ex)
            {
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = ex.Message.ToString();
                OAjaxOut.Error = true;
            }

            return OAjaxOut;
        }


        public static AjaxOut DrawWorkflowHistory(string SiteId, string CmsDataId)
        {
            string Html = "";
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
                AjaxOut AjaxOutHistory = WorkflowBll.ServerSideGetWorkflowHistory(SiteId, OSiteParam.ConnectionString, CmsDataId, true);
                if (AjaxOutHistory.RetNumber > 0)
                {
                    Html +=
                       "<div class=\"CssWorkflowHistory\">\r\n" +
                            AjaxOutHistory.HtmlContent +
                       "</div>\r\n";
                }
                OAjaxOut.HtmlContent = Html;
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.HtmlContent = ex.Message.ToString();
            }
            return OAjaxOut;
        }


        public static AjaxOut DrawChangeHistory(string SiteId, string CmsDataId)
        {
            string Html = "";
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                string GroupDataId = (string)WebEnvironments.Request(SiteId, "gid");
                SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
                DataSaveHistoryCls[] DataSaveHistories = CmsUtility.CreateCmsBussinessProcess(SiteId).CreateCmsProcess(SiteId).ReadingDataSaveHistory(SiteId, CmsDataId);
                Html += "<div class=tabcontent>\r\n" +
                      " <h3>Lịch sử thay đổi bài viết ("+DataSaveHistories.Length.ToString("#,##0")+")</h3>\r\n";
                
                Html += "<table>\r\n" +
                        "<tr>\r\n" +
                        "   <th>#</th>\r\n" +
                        "   <th>Số văn bản</th>\r\n" +
                        "   <th>Người thay đổi</th>\r\n" +
                        "   <th>Ngày thay đổi</th>\r\n" +
                        "   <th></th>\r\n" +
                        "</tr>\r\n";
                for (int iIndex = 0; iIndex < DataSaveHistories.Length; iIndex++)
                {
                    Html+=
                        "<tr>\r\n" +
                        "   <td>"+(iIndex+1)+"</td>\r\n" +
                        "   <td>" + DataSaveHistories[iIndex].Subject + "</td>\r\n" +                        
                        "   <td>"+ DataSaveHistories[iIndex].SaveByFullName + "</td>\r\n" +
                        "   <td>" + DataSaveHistories[iIndex].SaveDate.ToString("dd/MM/yyyy HH:mm") + "</td>\r\n" +
                         "   <td class=\"tdButton\"><input class=\"button\" type=\"button\" value=\"Xem\" onclick=\"javascript:PreviewVersionCmsData('" + GroupDataId + "','" + DataSaveHistories[iIndex].DataId + "','" + DataSaveHistories[iIndex].DataSaveHistoryId + "')\"></th>\r\n" +
                        "</tr>\r\n";
                }
                Html += "</table>\r\n" +
                        "</div>\r\n"; 

                OAjaxOut.HtmlContent = Html;
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.HtmlContent = ex.Message.ToString();
            }
            return OAjaxOut;
        }
    }
}
